/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package epaper;

import java.util.ArrayList;
import java.util.Collections;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Observable;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 *
 * @author Punit
 */
public abstract class CommonClient implements Callable{

    public static final List<String> files = Collections.synchronizedList(new ArrayList<String>());
    public static final List<InputStream> pdfs = Collections.synchronizedList(new ArrayList<InputStream>());
    public static String basefile = "C:\\";
    protected static int pagecount = 30;
    public static byte[][] buf = new byte[pagecount][];
    protected static List<Future<ByteArrayInputStream>> futures = new ArrayList<Future<ByteArrayInputStream>>();
    //private static final Date date = new Date();
    protected static StringBuilder urlStr = null;
    protected static StringBuilder mergePaper = null;
    protected String lang, fileName;
    protected int city;
    protected Date date;

    

    protected static enum Language {

        ENGLISH, HINDI,
    }
    protected static Language language;



    protected CommonClient(String lang, int city, String fileName, Date date) {
        this.lang = lang;
        this.city = city;
        this.fileName = fileName;
        this.date = date;
        WorkProgress.getInstance().setIncrAmount(900/pagecount);
        WorkProgress.getInstance().addObserver(UI.getInstance());
        
    }

    abstract public void buildURL(String lang, int city, Date date);
        


    abstract public  String buildPageUrl(int pagenumber);

    

    public String getThreeDigitString(int no) {
        if (no >= 0 && no <= 9) {
            return "00" + no;

        } else if (no <= 99) {
            return "0" + no;
        } else {
            return "Error";
        }

    }

    /**
     * @param args the command line arguments
     */
    public String call() throws ExecutionException {

        System.out.println("********************************************************");
        System.out.println("***********    CREATED BY -- Punit Agrawal   ***********");
        System.out.println("*******    Contact me @ punit.agrawal@gmx.com  *********");
        System.out.println("********************************************************");
        System.out.println("");
        //String[] arg = {"MAIN","ENG","MUM"};



        basefile = fileName;
        if (!fileName.endsWith("\\") && !fileName.endsWith("/")) {
            basefile += "/";
        }



        buildURL(lang, city, date);
        System.out.println("GETTING PDFs !!!! ");
        ExecutorService es = Executors.newFixedThreadPool(pagecount);
        
        for (int i = 0; i < pagecount; i++) {
            final String localStr = buildPageUrl(i+1);
            Callable<ByteArrayInputStream> c = new Worker(localStr, i);
            futures.add(es.submit(c));
        }

        for (Future<ByteArrayInputStream> f : futures) {
            try {
                InputStream i = f.get();
                if (i != null) {
                    pdfs.add(i);
                }
            } catch (InterruptedException ex) {
                //Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ExecutionException ex) {
                //Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                if(!(ex.getCause() instanceof NullPointerException))
                    throw ex;
            }
        }

        es.shutdown();

        //Combine the pdfs
        UI.getInstance().setTaskInProgress("Merging PDFs");
        System.out.println("MERGING PDFs");
        MyPDFUtility.mergeStreams(pdfs, mergePaper.toString());
        WorkProgress.getInstance().increment(100);
        System.out.println("PDFs MERGED");
        UI.getInstance().setTaskInProgress("PDFs Merged");
        
        return mergePaper.toString().replace('\\',File.separatorChar).replace('/', File.separatorChar);
    }

    
}
